<template>
  <el-form
    ref="form"
    class="item-container"
    :model="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit.prevent="onSubmit"
  >
    <!-- 手机号 -->
    <el-form-item prop="phone">
      <el-input v-model="formData.phone" :maxlength="11" size="large" placeholder="请输入手机号">
        <template #prefix>
          <el-icon><iphone /></el-icon>
        </template>
      </el-input>
    </el-form-item>

    <!-- 短信验证码 -->
    <el-form-item class="verification-code" prop="code">
      <el-input v-model="formData.code" size="large" placeholder="请输入短信验证码">
        <template #prefix>
          <el-icon><key /></el-icon>
        </template>
      </el-input>
      <el-button :disabled="countDown > 0" @click="handleCounter">
        {{ countDown === 0 ? '获取验证码' : `${countDown}秒后重发` }}
      </el-button>
    </el-form-item>

    <!-- 密码 -->
    <el-form-item prop="password">
      <el-input
        v-model="formData.password"
        size="large"
        :type="showPsw ? 'text' : 'password'"
        placeholder="请输入密码 (6-20位)"
      >
        <template #prefix>
          <el-icon><lock /></el-icon>
        </template>
        <template #suffix>
          <el-icon v-if="showPsw" @click="showPsw = !showPsw"><view /></el-icon>
          <el-icon v-else @click="showPsw = !showPsw"><hide /></el-icon>
        </template>
      </el-input>
    </el-form-item>

    <!-- 确认密码 -->
    <el-form-item prop="confirmPassword">
      <el-input
        v-model="formData.confirmPassword"
        size="large"
        :type="showConfirmPsw ? 'text' : 'password'"
        placeholder="请确认密码"
      >
        <template #prefix>
          <el-icon><lock /></el-icon>
        </template>
        <template #suffix>
          <el-icon v-if="showConfirmPsw" @click="showConfirmPsw = !showConfirmPsw"><view /></el-icon>
          <el-icon v-else @click="showConfirmPsw = !showConfirmPsw"><hide /></el-icon>
        </template>
      </el-input>
    </el-form-item>

    <!-- 协议勾选 -->
    <el-form-item class="check-container" prop="checked">
      <el-checkbox v-model="formData.checked">我已阅读并同意 </el-checkbox>
      <span>《用户协议》</span> 和 <span>《隐私政策》</span>
    </el-form-item>

    <!-- 注册按钮 -->
    <el-form-item>
      <el-button type="primary" :loading="loading" size="large" style="width: 100%" @click="onSubmit">
        {{ loading ? '注册中...' : '立即注册' }}
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus';
import { View, Hide, Lock, Key, Iphone } from '@element-plus/icons-vue';
import { ref } from 'vue';

import { register, type RegisterBody } from '../api/login';
import { useCounter } from '../hooks/useCounter';

const equalToPassword = (_rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入您的密码'));
  } else if (value !== formData.value.password) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const validatePhone = (_rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入手机号'));
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'));
  } else {
    callback();
  }
};

const validatePassword = (_rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'));
  } else if (value.length < 6 || value.length > 20) {
    callback(new Error('密码长度为6-20位'));
  } else {
    callback();
  }
};

const FORM_RULES = {
  phone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
  code: [{ required: true, message: '请输入短信验证码', trigger: 'blur' }],
  password: [{ required: true, validator: validatePassword, trigger: 'blur' }],
  confirmPassword: [{ required: true, validator: equalToPassword, trigger: 'blur' }],
  checked: [
    {
      validator: (_rule: any, value: boolean, callback: any) => {
        if (!value) {
          callback(new Error('请同意用户协议和隐私政策'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
};

const loading = ref(false);
const form = ref();
const formData = ref({
  phone: '',
  password: '',
  confirmPassword: '',
  code: '',
  checked: false,
});
const showPsw = ref(false);
const showConfirmPsw = ref(false);

const [countDown, handleCounter] = useCounter();

const emit = defineEmits(['registerSuccess']);

const onSubmit = async () => {
  try {
    await form.value?.validate();
  } catch {
    return;
  }

  if (!formData.value.checked) {
    ElMessage.error('请同意用户协议和隐私政策');
    return;
  }

  loading.value = true;
  const registerForm: RegisterBody = {
    username: formData.value.phone,
    code: formData.value.code,
    password: formData.value.password,
    userType: 'sys_user',
  };

  register(registerForm)
    .then(() => {
      ElMessage.success(`恭喜你，您的账号 ${registerForm.username} 注册成功！`);
      emit('registerSuccess');
    })
    .catch(() => {
      loading.value = false;
    });
};
</script>

<style lang="less" scoped>
.item-container {
  width: 100%;

  .check-container {
    display: flex;
    align-items: center;
    font: 14px var(--el-font-family);
    color: var(--el-text-color-regular);

    :deep(.el-checkbox__label) {
      padding-left: 8px;
    }

    span {
      color: var(--el-color-primary);
      cursor: pointer;
    }
  }

  .verification-code {
    display: flex;
    align-items: center;
    gap: 12px;

    :deep(.el-form-item__content) {
      flex: 1;
      display: flex;
      gap: 12px;
    }

    .el-input {
      flex: 1;
    }

    .el-button {
      flex-shrink: 0;
      width: 120px;
    }
  }
}
</style>
